package chances.wechat.service;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import chances.wechat.entity.QrCodeInfo;
import chances.wechat.repository.QrCodeRepository;

@Service("qrCodeFactory")
public class WechatQrCodeFactory implements QrCodeFactory {

	@Autowired
	QrCodeRepository qrCodeRepository;

	@Value("${qr.dir}")
	Resource qrdir;

	Map<String, Resource> staticQrCodes = new HashMap<String, Resource>();

	/*
	 * (non-Javadoc)
	 * 
	 * @see mgaic.weixin.service.QrCodeFactory#pickQrCode(chances.weixin.entity.
	 * QrCodeInfo)
	 */
	public QrCodeInfo pickQrCode(QrCodeInfo qrCodeInfo) throws IOException {
		QrCodeInfo qrInfo = qrCodeRepository.getQrCodeByQrInfo(qrCodeInfo
				.getQrInfo());
		qrCodeInfo.getQrInfo();
		if (qrInfo == null) {
			qrInfo = qrCodeInfo;
			qrCodeRepository.insertQrCode(qrCodeInfo);
		} else {
			qrCodeRepository.refreshQrInfo(qrInfo);
		}
		return qrInfo;
	}

	public File saveQrImage(QrCodeInfo qrCodeInfo) throws IOException {
		/*String scene = qrCodeInfo.getQrInfo();
		File aFile = new File(getQrDir(), scene + ".jpg");
		Date createTime = qrCodeInfo.getUpdateTime();
		if (aFile.exists()
				&& System.currentTimeMillis() - createTime.getTime() < timeOut) {
			return aFile;
		}
		GwResponse response = gatewayService.getQrCode(scene);
		if (!aFile.toURI().toString().equals(response.getResURI())) {
			FileOutputStream out = new FileOutputStream(aFile);
			try {
				CopyHelper.copy(aFile, response);
				logger.info("save Qrcode:" + aFile.getAbsolutePath());
			} finally {
				IOUtils.closeQuietly(out);
			}
		}
		if (aFile.exists()) {
			resizeQr(aFile);
		}
		return aFile;*/
		return null;
	}

	private File getQrDir() throws RuntimeException {
		try {
			return qrdir.getFile();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public File getQrCode(QrCodeInfo qrCodeInfo) {
		File aFile = new File(getQrDir(), qrCodeInfo.getQrInfo() + ".jpg");
		if(!aFile.exists()){
			try {
				this.saveQrImage(qrCodeInfo);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return aFile;
	}

	@Override
	public void updateScanTime(String scanCode) {
		qrCodeRepository.updateScanTime(scanCode);
	}

}
